package com.ruoyi.group.service.impl;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.group.domain.BusGoods;
import com.ruoyi.group.domain.GoodsAndStore;
import com.ruoyi.group.domain.StockBillItem;
import com.ruoyi.group.mapper.BusGoodsMapper;
import com.ruoyi.group.service.IBusGoodsService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.group.mapper.StockBillMapper;
import com.ruoyi.group.domain.StockBill;
import com.ruoyi.group.service.IStockBillService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 出入库单据Service业务层处理
 *
 * @author Zzz
 * @date 2022-11-28
 */
@Service
public class StockBillServiceImpl extends ServiceImpl<StockBillMapper, StockBill> implements IStockBillService {


    @Autowired
    private StockBillMapper stockBillMapper;
    @Autowired
    private BusGoodsMapper goodsMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IBusGoodsService goodsService;

    /**
     * 查询出入库单据列表
     *
     * @param stockBill 出入库单据
     * @return 出入库单据
     */
    @Override
    public List<StockBill> selectStockBillList(StockBill stockBill) {
        List<StockBill> stockBills = getBaseMapper().selectStockBillList(stockBill);
        for (StockBill stockBill1 : stockBills) {
            BigDecimal money = new BigDecimal(0);
            Integer count = 0;
            List<StockBillItem> stockBillItems = stockBillMapper.selectMoneyAndCount(stockBill1.getId());
            for (StockBillItem stockBillItem : stockBillItems) {
                count += stockBillItem.getCount();
                BigDecimal decimal = stockBillItem.getPrice().multiply(new BigDecimal(stockBillItem.getCount()));
                money = money.add(decimal);
            }
            stockBill1.setMoney(money);
            stockBill1.setCount(count);
        }
        return stockBills;
    }

    @Transactional
    @Override
    public boolean save(StockBill entity) {
        if (entity.getType() == 0) {
            //保存出入库信息
            Long userId = SecurityUtils.getUserId();
            entity.setOperatorId(userId);
            entity.setType(0);
            entity.setOperateDate(new Date());
            entity.setStatus(0);
            super.save(entity);
            //保存订单明细表
            List<StockBillItem> list = entity.getList();
            for (StockBillItem stockBillItem : list) {
                Integer i = stockBillMapper.selectJudge(entity.getStoreId(), stockBillItem.getGoodsId());
                if (i!=null){
                    throw new ServiceException("此仓库已有其中一个物品但价格不一样");
                }
                Long id = goodsMapper.selectId(stockBillItem.getGoodsName());
                stockBillItem.setGoodsId(String.valueOf(id));
                stockBillItem.setBillId(String.valueOf(entity.getId()));
                stockBillItem.setState(false);
                System.out.println(stockBillItem);
                stockBillMapper.saveItem(stockBillItem);
                //物品仓库关系
                GoodsAndStore goodsAndStore = stockBillMapper.selectRelation(stockBillItem.getGoodsId(), entity.getStoreId());
                if (goodsAndStore != null) {
                    stockBillMapper.updateRelation(goodsAndStore.getId(), stockBillItem.getCount());
                } else {
                    stockBillMapper.saveRelation(stockBillItem.getGoodsId(), entity.getStoreId(), stockBillItem.getCount());
                }
            }
        } else {
            //保存出入库信息
            Long userId = SecurityUtils.getUserId();
            entity.setOperatorId(userId);
            entity.setType(1);
            entity.setOperateDate(new Date());
            entity.setStatus(0);
            super.save(entity);
            //保存订单明细表
            List<StockBillItem> list = entity.getList();
            for (StockBillItem stockBillItem : list) {
                Long id = goodsMapper.selectId(stockBillItem.getGoodsName());
                stockBillItem.setGoodsId(String.valueOf(id));
                stockBillItem.setBillId(String.valueOf(entity.getId()));
                stockBillItem.setState(false);
                System.out.println(stockBillItem);
                stockBillMapper.saveItem(stockBillItem);
                //物品仓库关系
                GoodsAndStore goodsAndStore = stockBillMapper.selectRelation(stockBillItem.getGoodsId(), entity.getStoreId());
                if (goodsAndStore != null) {
                    if (goodsAndStore.getAmounts() < stockBillItem.getCount()) {
                        throw new ServiceException("此仓库物品不够");
                    }
                    stockBillMapper.removeRelation(goodsAndStore.getId(), stockBillItem.getCount());
                } else {
                    throw new ServiceException("此仓库没有该物品,不能出库");
                }
            }
        }

        return true;
    }
    @Transactional
    @Override
    public StockBill getById(Long id) {
        StockBill bill = super.getById(id);
        List<StockBillItem> stockBillItems = stockBillMapper.selectMoneyAndCount(id);
        for (StockBillItem stockBillItem : stockBillItems) {
            String name = goodsMapper.selectName(stockBillItem.getId());
            stockBillItem.setGoodsName(name);
        }
        bill.setList(stockBillItems);
        return bill;
    }
    @Transactional
    @Override
    public boolean removeBatchByIds(Long id) {
        StockBill stockBill = this.getById(id);
        String storeId = stockBill.getStoreId();
        //遍历单据
        List<StockBillItem> list = stockBill.getList();
        for (StockBillItem stockBillItem : list) {
            int itemCount = stockBillMapper.selectItemCount(stockBill.getId(),stockBillItem.getGoodsId());
            int count = stockBillMapper.selectStoreCount(storeId,stockBillItem.getGoodsId());
            if (itemCount > count) {
                throw new ServiceException("有物品库存数量不足");
            }
            GoodsAndStore goodsAndStore = stockBillMapper.selectRelation(stockBillItem.getGoodsId(), stockBill.getStoreId());
            if (stockBill.getType() == 0) {
                stockBillMapper.removeRelation(goodsAndStore.getId(), itemCount);
            } else {
                stockBillMapper.updateRelation(goodsAndStore.getId(), itemCount);
            }
        }
        LambdaUpdateWrapper<StockBill> wrapper =new LambdaUpdateWrapper<>();
        wrapper.set(StockBill::getStatus,-1).eq(StockBill::getId,stockBill.getId());
        getBaseMapper().update(stockBill,wrapper);
        return true;
    }
}
